//
//  LHUserAccount.swift
//  sina_weibo
//
//  Created by 刘刘海强 on 16/5/12.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

import UIKit

class LHUserAccount: NSObject, NSCoding {
    
    //字典转模型的声明
    var access_token: String?
    var expires_in: NSTimeInterval = 0 {
        didSet {
            exeiresDate = NSDate().dateByAddingTimeInterval(expires_in)
        }
    }
    var exeiresDate: NSDate?
    var uid: Int64 = 0
    
    //获取用户数据后赋值给模型的属性
    var name: String?
    var avatar_large: String?
    
   //kvc构造函数
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    override var description: String {
        let keys = ["access_token","expires_in","uid","name","avatar_large"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
    //归档、解档：NSCoding的代理方法
    //NSKeyedArchiver.archiveRootObject方法执行时调用下述方法
    func encodeWithCoder(acoder: NSCoder) {
        acoder.encodeObject(access_token, forKey: "access_token")
        acoder.encodeObject(exeiresDate, forKey: "exeiresDate")
        acoder.encodeInt64(uid, forKey: "uid")
        acoder.encodeObject(name, forKey: "name")
        acoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    //NSKeyedUnarchiver.unarchiveObjectWithFile方法执行时调用下述方法
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        exeiresDate = aDecoder.decodeObjectForKey("exeiresDate") as? NSDate
        uid = aDecoder.decodeInt64ForKey("uid")
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
  
    }
    
    //保存用户数据
    func saveUserAccount() -> Bool {
        let path = ( NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString ).stringByAppendingPathComponent("userAccount.archiver")
        return NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    //读取用户数据
    class func loadUserAccount() -> LHUserAccount? {
        let path = ( NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString ).stringByAppendingPathComponent("userAccount.archiver")
        return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? LHUserAccount
    }
    
}









